package com.qf.anli.filter;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//@WebFilter("/index.html")
//@Component
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        //判断是否登录 （判断session中是否有用户的信息）
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        //放行一些不需要拦截的资源
        String requestURI = req.getRequestURI();
        if (requestURI != null){
            if (requestURI.endsWith("/login.html")){
                filterChain.doFilter(req,resp);
                return;
            }
        }


        HttpSession session = req.getSession();

        Object user = session.getAttribute("user");
        if(user == null){
            //没有登录，去到登录页面
            resp.sendRedirect("/login.html");

            return;
        }

        //已经登录，放行
        filterChain.doFilter(req,resp);
    }
}
